package com.fyzk.activity.fragment;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.SimpleClickListener;
import com.fyzk.activity.BluePrintDetailsActivity;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.lottery.recommend_order.OtherCenterActivity;
import com.fyzk.activity.popupwindow.FollowDocumentaryPopupWindow;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.adapter.DocumentaryAdapter;
import com.fyzk.base.BaseFragment;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.model.DocumentaryViewModel;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.widget.CustomLoadMoreView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * Created by Administrator on 2018/9/25.
 */
@ContentView(R.layout.fragment_documentary)
public class DocumentaryFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {
    @ViewInject(R.id.rv_race)
    RecyclerView mRvRace;
    @ViewInject(R.id.refresh_race)
    SwipeRefreshLayout mRefreshRace;
    private int mType;
    private int currentPager = 0;
    private int mCountData = 20;
    private DocumentaryAdapter mAdapter;
    private LinearLayoutManager mDocumentaryManager;
    private int mCurrentPageDataSize = 0;//当前页数据长度。
    private DocumentaryViewModel mDocumentaryViewModel;
    private View mEmptyView;
    private TextView mTvCocumentaryExplain;
    private TextView mTvGoDocumentary;

    public static DocumentaryFragment newInstance(int type) {

        Bundle args = new Bundle();
        args.putInt("type", type);
        DocumentaryFragment fragment = new DocumentaryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != getArguments()) {
            mType = getArguments().getInt("type");
        }
        return x.view().inject(this, inflater, container);//xutil注解;
    }

    private void initViews() {
        mRefreshRace.setOnRefreshListener(this);
        mRefreshRace.setColorSchemeColors(Color.RED);
        mAdapter = new DocumentaryAdapter();
        mDocumentaryManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRvRace.setLayoutManager(mDocumentaryManager);
        mRvRace.setAdapter(mAdapter);
        mEmptyView = LayoutInflater.from(getContext()).inflate(R.layout.item_empty_documentary, mRvRace, false);
        mTvCocumentaryExplain = mEmptyView.findViewById(R.id.tv_documentary_explain);
        mTvGoDocumentary = mEmptyView.findViewById(R.id.tv_go_documentary);
        mTvGoDocumentary.setOnClickListener(this);
        mAdapter.setOnLoadMoreListener(this, mRvRace);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.include_base_adapter_loading, mRvRace);
        findNewRecommendOrders(true);
        mRvRace.addOnItemTouchListener(new RVOnItemClickListener());
        mDocumentaryViewModel = ViewModelProviders.of(getActivity()).get(DocumentaryViewModel.class);
    }

    public void setNewType(int type) {
        mType = type;
        mRefreshRace.setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
    }

    /**
     * 查询晒单大厅 最新推荐
     *
     * @param showProgress
     */
    private void findNewRecommendOrders(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("raceType", mType);    // 类型（竞彩足球：1；竞彩篮球：2,不区分 3）
            request_json.put("startLine", currentPager);
            request_json.put("maxLine", mCountData);
            httpPostJson(CommandUtil.FINDNEWRECOMMENDORDERS, Commands.FINDNEWRECOMMENDORDERS, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRefresh() {
        currentPager = 0;
        mCurrentPageDataSize = 0;
        findNewRecommendOrders(false);
    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        List<MyRecommendOrderBean> beans = JSON.parseArray(resultBean.getData(), MyRecommendOrderBean.class);
        if (null != mRefreshRace) {
            mRefreshRace.setRefreshing(false);
        }
        if (null == beans || beans.size() == 0) {
            mCurrentPageDataSize = 0;
            if (currentPager == 0) {
                mAdapter.setNewData(null);
                if (mType == 3) {
                    mTvCocumentaryExplain.setText("暂无关注记录~~");
                    mTvGoDocumentary.setVisibility(View.GONE);
                } else {
                    mTvCocumentaryExplain.setText("暂无晒单记录~");
                    mTvGoDocumentary.setVisibility(View.GONE);
                }
                mAdapter.setEmptyView(mEmptyView);
            } else {
                mAdapter.loadMoreEnd();
            }
        } else {
            mCurrentPageDataSize = beans.size();
            if (currentPager == 0) {
                mAdapter.setNewData(beans);
                mAdapter.disableLoadMoreIfNotFullPage();
            } else {
                mAdapter.addData(beans);
                mAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public void onFailure(int requestCode, String errorCode, String message) {
        mCurrentPageDataSize = 0;
        if (null != mRefreshRace) {
            mRefreshRace.setRefreshing(false);
        }
        if (0 == currentPager) {
            mAdapter.setNewData(null);
            if (mType == 3) {
                mTvCocumentaryExplain.setText("暂无关注记录~~");
                mTvGoDocumentary.setVisibility(View.GONE);
            } else {
                mTvCocumentaryExplain.setText("暂无晒单记录~");
                mTvGoDocumentary.setVisibility(View.GONE);
            }
            mAdapter.setEmptyView(mEmptyView);
        } else {
            if ("5".equals(errorCode)) {
                mAdapter.loadMoreEnd();
            } else {
                mAdapter.loadMoreFail();
            }
        }
    }


    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        mCurrentPageDataSize = 0;
        if (null != mRefreshRace) {
            mRefreshRace.setRefreshing(false);
        }
        if (0 == currentPager) {
            mAdapter.setNewData(null);
            if (mType == 3) {
                mTvCocumentaryExplain.setText("暂无关注记录~~");
                mTvGoDocumentary.setVisibility(View.GONE);
            } else {
                mTvCocumentaryExplain.setText("暂无晒单记录~");
                mTvGoDocumentary.setVisibility(View.GONE);
            }
            mAdapter.setEmptyView(mEmptyView);
        } else {
            mAdapter.loadMoreFail();
        }
    }

    /**
     * RecyclerView的点击事件
     */
    private class RVOnItemClickListener extends SimpleClickListener {

        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            List<MyRecommendOrderBean> mData = adapter.getData();
            Intent intent = new Intent(getContext(), BluePrintDetailsActivity.class);
            intent.putExtra(IntentParamUtils.USERNO, mData.get(position).getUserno());
            intent.putExtra(IntentParamUtils.RECOMMENDINFOR, mData.get(position));
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {

        }

        @Override
        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
            MyRecommendOrderBean item = mAdapter.getItem(position);
            Intent intent;
            switch (view.getId()) {
                case R.id.iv_avatar:
                    intent = new Intent(getContext(), OtherCenterActivity.class);
                    if (null != item) {
                        intent.putExtra(IntentParamUtils.USERNO, item.getUserno());
                        intent.putExtra("isExpert", item.getIsexpert());
                        intent.putExtra(IntentParamUtils.RECOMMENDINFOR, item);
                        startActivity(intent);
                    }
                    break;
                case R.id.tv_made_the_documentary:
//                    intent = new Intent(getContext(), RecommendDetailActivity.class);
//                    intent.putExtra(IntentParamUtils.RECOMMENDINFOR, mData.get(position));
//                    startActivity(intent);
                    showFollowDocumentaryPopup(item);
                    break;
            }
        }

        @Override
        public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {

        }
    }

    FollowDocumentaryPopupWindow followDocumentaryPopupWindow;

    /**
     * 展示跟单的弹窗
     *
     * @param item 跟单内容
     */
    private void showFollowDocumentaryPopup(MyRecommendOrderBean item) {
        if (null == item)
            return;
        if (TextUtils.equals(item.getUserno(), MySharedPreferences.getInstance().getUserNo())) {
            showToast("不能跟自己的单！");
            return;
        }
        followDocumentaryPopupWindow = new FollowDocumentaryPopupWindow(getActivity(), item);
        followDocumentaryPopupWindow.showPopupWindow();
    }

    @Override
    public void onLoadMoreRequested() {
        if (null != mAdapter && null != mAdapter.getData()) {
//            currentPager += mCurrentPageDataSize;
            currentPager = mAdapter.getData().size();
        }
        findNewRecommendOrders(false);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (3 == mType) {
            if (isVisibleToUser) {
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    mDocumentaryViewModel.onRequestLogin();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.tv_go_documentary) {
            Intent intent = new Intent();
            if (MySharedPreferences.getInstance().getLoginStatus()) {
                mDocumentaryViewModel.onRequestGotoBaskInASingle();
            } else {
                AppLotteryInfos.clear();
                ViewCallBack.getInstance().countDownObjs.clear();
                ActivityTaskManager.getInstance().closeAllActivity();
                intent.setClass(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        }
    }
}
